package com.damagedboy.base.utils.dao;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.namedparam.BeanPropertySqlParameterSource;
import org.springframework.jdbc.core.simple.SimpleJdbcInsert;
import org.springframework.stereotype.Repository;

import java.io.Serializable;

@Repository
public class CommonDaoImpl<T> implements ICommonDao<T> {
    @Autowired
    JdbcTemplate jdbcTemplate;

    @Override
    public int insert(String tableName, Object o) {
        SimpleJdbcInsert jdbcInsert = new SimpleJdbcInsert(jdbcTemplate);
        jdbcInsert.withTableName(tableName);
        jdbcInsert.usingGeneratedKeyColumns("id");
        Number number = jdbcInsert.executeAndReturnKey(new BeanPropertySqlParameterSource(o));
        return number.intValue();
    }

    @Override
    public int delById(String tableName, Serializable id) {
        return jdbcTemplate.update("DELETE FROM " + tableName + " where id=?", id);
    }

    @Override
    public T getById(String taleName, Integer id, Class c) {
        return (T) jdbcTemplate.queryForObject("select * from " + taleName + "where id=?", new Object[]{id},
                BeanPropertyRowMapper.newInstance(c));
    }
}
